#include <iostream>
#include <cstdlib> // for rand

#include "Server.h"
#include "../Common/Util/Logger.h"
#include "../Common/Util/Singulator.h"

#include "Physics/PhysicsEngine.h"
#include "Physics/PhysicsLocale.h"

#include <ace/ACE.h>
#include <ace/OS_NS_unistd.h>
#include <ace/Signal.h>

using namespace std;
using namespace Tool;
using namespace Physics;

static sig_atomic_t bQuit = false;

extern "C" void handler (int)
{
	bQuit = true;
}

ServerApp::ServerApp()
{
		ACE::init();
	    Singulator<Logger>::init();
		LOGINFO("Start Logging");
		
		Singulator<Physics::PhysicsEngine>::init();
}

ServerApp::~ServerApp()
{
	LOGINFO("End Logging");
    Singulator<Logger>::destroy();

	LOGINFO("Physics::PhysicsEngine End");
	Singulator<Physics::PhysicsEngine>::destroy();
}

bool CtrlHandler( DWORD fdwCtrlType ) 
{ 
  bQuit = true;
  return(true );
} 
  

int main(int argc, char* argv[]) 
{

	if (ACE::init() < 0) 
		return -1;
	// signalhandler for CTRL-C
	ACE_Sig_Action sa ((ACE_SignalHandler) handler, SIGINT);


	ServerApp server;
	Tool::Logger& log = Singulator<Tool::Logger>::content();
	Physics::PhysicsEngine& physics = Singulator<Physics::PhysicsEngine>::content();
	log.setProgramName("VoidServer");
	srand(time(0));  // Initialize random number generator.

	
	bQuit = false;


long long testobjectid;
long long testlocaleid;
PhysicsObject* testobject;
NxVec3 randomvect;
PhysicsLocale* testlocale;

for (unsigned int x = 0; x < 10; x++)
{
	testlocaleid = 	physics.createLocale();
	cout << "Created new locale. ID = " << testlocaleid << endl;
	testlocale = physics.getLocale(testlocaleid);

	for (unsigned int i = 0; i < 100; i++)
	{
		testobjectid = physics.createObject();
		//cout << "Created new object: " << testobjectid << endl;
		testobject = physics.getObject(testobjectid);		
		randomvect.set((rand() % 100) + 1, (rand() % 100) + 1, (rand() % 100) + 1);
		testlocale->addObject(testobjectid, randomvect);
		randomvect.set((rand() % 10) + 1, (rand() % 10) + 1, (rand() % 10) + 1);
		testobject->m_actor->setLinearVelocity(randomvect);
	}
}


server.networkthread.activate();
physics.activate();


	while (!bQuit)
	{
		ACE_OS::sleep(1);
		cout << ".";
	}

//	g_reactor->notify();
//	server.networkthread


	physics.quit();

	return 0;
}